<!-- 退货管理--退货单操作--审核/收货（开红票/不开红票） -->
<template>
  <div class="auth-product return-goods-box">
    <el-container class="partDetails is-vertical">
      <read-form
        class="custom-info"
        :record-form="returnGoodsInfoColumns"
        :record-data="headerInfo">
        <template slot="recordInfoslot">
          <div
            class="solt-info">
            <span class="left-span">
              退货产品总数：
              <span class="right-span">{{ headerInfo.orderDetailCount }}</span>
            </span>
            <span>
              品种数：
              <span>{{ headerInfo.returnCount }}</span>
            </span>
            <span>
              金额合计 （元）:
              <span>
                <span class="price">{{ headerInfo.returnAmount | getFormatterPrice }}</span>
              </span>
            </span>
            <el-button
              v-if="isRed"
              size="mini"
              type="primary"
              class="batch-btn"
              @click="batchAddInvoice"
            >批量添加发票号</el-button>
          </div>
        </template>
      </read-form>
      <el-editable
        class="distributor-edit-box"
        :key="isRed"
        :data="returnGoodsList"
        height="400"
        v-loading="tableLoading"
        :columns="activeTableColumns"
        @selection-change="changeSelect"
      >
        <template
          slot="default-invoiceCode"
          slot-scope="scope">
          <el-input
            :disabled="!scope.row.isEditInvoice"
            v-model="scope.row.invoiceCode"
            style="width: 120px;"
            size="mini"
            :title="scope.row.invoiceCode"
          />
          <el-button
            v-if="scope.row.isEditInvoice"
            size="mini"
            @click="toSaveInvoice(scope.row.invoiceCode, [scope.row])">确定</el-button>
          <el-button
            v-else
            size="mini"
            @click="scope.row.isEditInvoice = true">编辑</el-button>
        </template>
        <template
          slot="default-registrationNumber"
          slot-scope="scope">
          <el-button
            :disabled="!scope.row.registrationNumber||!scope.row.registrationId"
            v-html="regisNoButton(scope.row, 'registration')"
            @click="showPdfRegistion(scope.row.registrationId)"
            type="text"
          />
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <pagination
        ref="page"
        :request-func="getList"
        @returnData="getTableData"
      />
    </el-container>
    <el-dialog
      title="批量关联发票号"
      :visible.sync="batchDialogVisible"
      width="50%"
      @close="handleClose">
      <el-form
        :model="batchInvoiceForm"
        label-width="100px">
        <el-form-item :label="'发票号'">
          <el-input
            style="width: 300px;"
            v-model="batchInvoiceForm.invoiceCode"/>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer">
        <el-button @click="handleClose">
          <i class="el-icon-circle-close"/>
          取 消</el-button>
        <el-button
          type="primary"
          @click="toSaveInvoice(batchInvoiceForm.invoiceCode)">
          <i class="el-icon-circle-check"/>
          确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="审核拒绝"
      :visible.sync="checkDialogVisible"
      width="50%"
      @close="handleCheckClose">
      <el-form
        :model="checkForm"
        label-width="100px">
        <el-form-item :label="'备注'">
          <el-input
            type="textarea"
            style="width: 300px;"
            v-model="checkForm.remarks"/>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer">
        <el-button @click="handleCheckClose">
          <i class="el-icon-circle-close"/>
          取 消</el-button>
        <el-button
          type="primary"
          @click="rejectCheck()">
          <i class="el-icon-circle-check"/>
          确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  statusArr,
  orderTypeData,
  invoiceFlagObj,
  returnGoodsEditRedTableColumns,
  returnGoodsNoRedTableColumns,
  returnGoodsInfoColumns
} from './const'
import Pagination from '@components/custom-pagination'
import ReadForm from '@/moduleComponents/beforeSettle/common/read-form'
import {
  returnGoodsCheck, // 配送商-退货管理-退货单审核
  returnGoodsInfo, // 配送商-退货管理-订单详情
  returnGoodsItemDetail, // 配送商-退货管理-订单明细详情带分页
  returnGoodsReceice, // 配送商-退货管理-收货
  returnGoodsUpdateInvoiceCode // 配送商-退货管理-开红票-更新发票号
} from '@const/beforeSettleApi'
import ElEditable from '@components/el-editable'
import { cloneDeep, isObject, hasIn } from 'lodash'
import { formatPrice, regisNoButton, showPdfRegistion } from '@const/agencySaas'
import { getFormatterPrice } from '@const/filter'
export default {
  components: { ElEditable, Pagination, ReadForm },
  data () {
    return {
      id: this.$route.query.id,
      orderStatus: null,
      // 防止重复交互
      isRequest: true,
      // 表格Loading
      tableLoading: false,
      returnGoodsEditRedTableColumns,
      returnGoodsNoRedTableColumns,
      selectList: [],
      // 表单 详情展示内容-table
      returnGoodsList: [],
      // 订单详情信息
      headerInfo: {},
      returnGoodsInfoColumns,
      orderType: null,
      invoiceFlag: null,
      // 批量设置发票号
      batchInvoiceForm: { invoiceCode: null },
      batchDialogVisible: false,
      // 审核
      checkDialogVisible: false,
      checkForm: {
        remarks: ''
      }
    }
  },
  filters: {
    getFormatterPrice
  },
  computed: {
    isRed () {
      // 1.orderStatus:3-待收货 2.orderType:3，4-采购（类型还未定） 3.invoiceFlag: 1-开红票
      return [3].includes(this.orderStatus) && [3, 4].includes(this.orderType) && [1].includes(this.invoiceFlag)
    },
    activeTableColumns () {
      return this.isRed ? this.returnGoodsEditRedTableColumns : this.returnGoodsNoRedTableColumns
    }
  },
  mounted () {
    this.getBaseInfo(this.initGlobalBtns)
  },
  methods: {
    formatPrice,
    regisNoButton,
    showPdfRegistion,
    initGlobalBtns (status = this.orderStatus) {
      // 开票订单状态（1-待审核，2-待发货，3-待收货，4-已完成 , 5-已撤消，6-已拒绝）
      // 1-status 审核拒绝;审核通过
      // 3-status 确定收货
      let arr = [3].includes(status) ? [{ type: 'primary', val: '确定收货', handle: this.toReceive }]
        : [1].includes(status) ? [
          { type: 'primary', val: '审核拒绝', handle: this.toRejectCheck },
          { type: 'primary', val: '审核通过', handle: this.passCheck }
        ]
          : []
      const btn = {
        type: 'btn',
        arr
      }
      this.$store.commit('changeLayoutHandle', btn)
    },
    // 列表请求方法
    getList () {
      this.tableLoading = true
      const body = {
        id: this.id,
        ...this.$refs.page.page
      }
      return this.$axios.$post(returnGoodsItemDetail, body)
    },
    // 列表请求方法
    getTableData (data) {
      this.returnGoodsList = data
      this.returnGoodsList.forEach(item => {
        this.$set(item, 'isEditInvoice', false)
      })
      this.tableLoading = false
    },
    // 审核弹窗
    toRejectCheck () {
      this.checkDialogVisible = true
    },
    // 审核弹窗
    rejectCheck () {
      const checkOrder = 1
      const remarks = this.checkForm.remarks
      this.toCheck({ checkOrder, remarks })
    },
    passCheck () {
      const checkOrder = 0
      this.toCheck({ checkOrder })
    },
    // 审核
    async toCheck ({ id = this.id, checkOrder, remarks } = {}) {
      if (!this.isRequest) {
        return void this.$message.warning('请稍后再试')
      }
      this.isRequest = false
      try {
        const body = {
          id,
          checkOrder,
          remarks
        }
        const responseData = await this.$axios.$post(returnGoodsCheck, body)
        responseData.code === '0' && this.$router.go(-1)
      } finally {
        this.isRequest = true
        this.checkDialogVisible = false
      }
    },
    handleCheckClose () {
      this.checkDialogVisible = false
      this.checkForm = {
        remarks: ''
      }
    },
    // 批量添加发票号弹窗
    async toReceive () {
      if (!this.isRequest) {
        return void this.$message.warning('请稍后再试')
      }
      const errorCode = this.returnGoodsList.filter(i => !i.invoiceCode)
      if (errorCode.length > 0 && this.isRed) {
        return void this.$message.warning('发票号必填才可以进行确定收货')
      }
      const editCode = this.returnGoodsList.filter(i => i.isEditInvoice)
      if (editCode.length > 0 && this.isRed) {
        return void this.$message.warning('请保存正在修改的发票号')
      }
      this.isRequest = false
      try {
        const body = {
          id: this.id
        }
        const responseData = await this.$axios.$post(returnGoodsReceice, body)
        responseData.code === '0' && this.$router.go(-1)
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequest = true
      }
    },
    // 批量添加发票号
    batchAddInvoice () {
      if (!this.selectList.length) {
        this.$message.warning('至少选择一项')
      } else {
        this.batchDialogVisible = true
      }
    },
    handleClose () {
      this.batchDialogVisible = false
      this.batchInvoiceForm = {
        invoiceCode: ''
      }
    },
    // 选择订单项
    changeSelect (data) {
      this.selectList = data
    },
    // 选择订单项
    async toSaveInvoice (invoiceCode, idList = this.selectList) {
      if (!this.isRequest) {
        return void this.$message.warning('请稍后再试')
      }
      this.isRequest = false
      const body = idList.map(({ id }) => {
        return {
          invoiceCode,
          orderItemId: id
        }
      })
      try {
        const data = await this.$axios.$post(returnGoodsUpdateInvoiceCode, body)
        if (data.code === '0') {
          this.$refs.page.Refresh()
          this.batchInvoiceForm = {
            invoiceCode: ''
          }
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.batchDialogVisible = false
        this.isRequest = true
      }
    },
    // 基本信息请求方法
    async getBaseInfo (fn) {
      this.tableLoading = true
      const body = {
        id: this.id
      }
      try {
        const data = await this.$axios.$post(returnGoodsInfo, body)
        const baseInfo = hasIn(data, 'payload') ? data.payload : {}
        Object.keys(baseInfo).forEach(key => {
          // 订单状态不展示
          if (key === 'orderStatus') {
            this.orderStatus = baseInfo[key]
            baseInfo[key] = statusArr[baseInfo[key]]
          }
          // 订单类型
          if (key === 'orderType') {
            this.orderType = baseInfo[key]
            baseInfo[key] = orderTypeData[baseInfo[key]]
          }
          // 是否开红票
          if (key === 'invoiceFlag') {
            this.invoiceFlag = baseInfo[key]
            baseInfo[key] = invoiceFlagObj[baseInfo[key]]
          }
          const type = typeof baseInfo[key]
          const value = ['number'].includes(type) ? baseInfo[key] : (baseInfo[key] || '--')
          this.$set(this.headerInfo, key, value)
        })
        fn && fn(this.orderStatus)
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style lang="less">
.return-goods-box {
  .partDetails {
    height: 100%;
    .custom-info {
      margin: 0;
      height: auto;
    }
    .batch-btn.el-button span {
      color: white;
      margin-right: 0;
      font-size: 14px;
    }
    .batch-btn.el-button {
      position: absolute;
      right: 10px;
    }
  }
}
</style>
